#include "Car.h"
#include <QPainter>
#include <QtMath>

Car::Car(qreal width, qreal height, QGraphicsItem* parent)
    : QGraphicsObject(parent), m_width(width), m_height(height)
{
    // 设置初始位置和变换中心
    setTransformOriginPoint(boundingRect().center());
    
    // 初始化外观
    QGraphicsLineItem* arrow = new QGraphicsLineItem(
        0, -m_height/2, 0, m_height/2, this);
    arrow->setPen(QPen(Qt::red, 2));
}

QRectF Car::boundingRect() const {
    return QRectF(-m_width/2, -m_height/2, m_width, m_height);
}

void Car::paint(QPainter* painter, 
               const QStyleOptionGraphicsItem* /*option*/,
               QWidget* /*widget*/) {
    // 绘制车身
    painter->setBrush(QColor(0, 150, 255));  // 设置车身颜色
    painter->setPen(Qt::NoPen);  // 不绘制边框
    painter->drawRoundedRect(boundingRect(), 5, 5);  // 绘制车身
}


void Car::setSpeed(qreal speed) {
    qreal newSpeed = qBound(-5.0, speed, 10.0);
    if (qFuzzyCompare(newSpeed, m_speed)) return;
    
    m_speed = newSpeed;
    emit speedChanged(m_speed);  // 发出信号
}

void Car::updatePosition() {
    qreal actualAngle = rotation() + m_steeringAngle * 0.7;
    if(actualAngle > 360)
        actualAngle -=360;

    if(actualAngle < -360)
        actualAngle += 360;
    // 更新车身旋转角度（新增代码）
    setRotation(actualAngle); // 保持车头与运动方向一致
    ///当前小车的角度
    std::cout<<"car angle = "<<actualAngle<<std::endl;
    
    QTransform transform;
    transform.rotate(actualAngle);
    m_velocity = transform.map(QPointF(m_speed, 0));
    setPos(pos() + m_velocity);

   // 输出车的新位置
    QPointF currentPosition = pos();  // 获取小车的位置
    std::cout << "car position = (" << currentPosition.x() << ", " << currentPosition.y() << ")" << std::endl;

    m_steeringAngle *= 0.85;
    m_steeringAngle = qBound(-35.0, m_steeringAngle, 35.0);
}

void Car::setSteering(qreal angle) {
    m_steeringAngle += angle;
}

QPointF Car::velocity() const {
    return m_velocity;
}